import React from "react";
import { useState, useCallback } from "react";
import DescriptionBox from "../../components/DescriptionBox";

const ButtonWithMemo = React.memo(({ onClick, label }: { onClick: () => void, label: string }) => {
    console.log('ButtonWithMemo 渲染');
    return <button onClick={onClick}>{label}</button>;
});

const UseCallbackDemo = () => {
    const [count, setCount] = useState(0);
    const [text, setText] = useState('');

    // 使用 useCallback 缓存函数
    const handleClick = useCallback(() => {
        console.log("🚀 ~ handleClick ~ useCallback:",);
        setCount(count + 1);
    }, [count]); // 只有 count 变化时才重新创建函数

    return (
        <>
            <div>
                <input value={text} onChange={(e) => setText(e.target.value)} />
                <ButtonWithMemo onClick={handleClick} label="增加计数 1" />
                <p>计数: {count}</p>
            </div>
            <DescriptionBox items={['使用 useCallback 缓存函数,只有 count 变化时才重新创建函数', 'Input 更新并不会触发子组件的渲染']}></DescriptionBox>
        </>
    );
};

export default UseCallbackDemo;